package com.service.callback;

import com.utils.LogUtil;
import com.websocket.wsCallBack;


/**
 * 内部会调用，每个txid对应于一个实例
 *
 * @author jby
 */
public class CallbackOfInner extends LogUtil {

    private static long timeout = 3 * 60;//回调的超时，可根据实际生产环境调整到5min
    private static long pulltime = 15;//拉取上链信息的延迟时间，可根据实际生产环境调整到30s
    private long start = 0l;
    private wsCallBack cb = null;
    private String txid = "";
    private long lastPullTime = 0l;
    private boolean isOnChain = false;

    public CallbackOfInner(wsCallBack cb, String txid) {
        this.cb = cb;
        this.txid = txid;
        this.start = System.currentTimeMillis();
    }

    private long getWaitTime() {
        return (System.currentTimeMillis() / 1000 - this.start / 1000);
    }

    /**
     * 订阅的超时
     *
     * @return
     */
    public boolean isTimeout() {
        return getWaitTime() > timeout;
    }

    /**
     * 拉取的超时
     *
     * @return
     */
    public boolean isPullTimeout() {
        if (this.lastPullTime == 0) {
            return getWaitTime() > pulltime;
        } else {
            return (System.currentTimeMillis() / 1000 - this.lastPullTime / 1000) > pulltime;
        }
    }

    public void onChainSuccess() {
        this.isOnChain = true;
    }

    public void onCallback() {
        try {
            this.cb.onChain(this.txid, this.isOnChain);
        } catch (Exception e) {
            logMsg("error", "{} ~" + "CallbackOfInner:onCallback falied ,error msg={}", this.txid, e.getMessage());
        }
    }

    public String getTxid() {
        return this.txid;
    }


    /**
     * 修改上链状态
     *
     * @return
     */
    public boolean callbackStatus() {
        return this.isOnChain;
    }

    public void setPullLastTime() {
        this.lastPullTime = System.currentTimeMillis();
    }
}
